package org.dragonnova.lamp.utils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Created by hucn on 2016/7/29.
 * Description:
 */
public class WifiUtil {

    public static String convertIntIpAddress(int ipAdress) {
        return (ipAdress & 0xFF) + "." +
                ((ipAdress >> 8) & 0xFF) + "." +
                ((ipAdress >> 16) & 0xFF) + "." +
                (ipAdress >> 24 & 0xFF);
    }

    public static byte[] convertIntIpToBytes(int ipAdress) {
        byte[] result = new byte[4];
        for (int i = 0; i < 4; i++) {
            result[i] = (byte) ((ipAdress >> i * 8) & 0xFF);
        }
        return result;
    }

    public static int byte2Int(byte[] b) {
        if (b.length == 1) {
            return b[0] & 0xff;
        } else if (b.length == 2) {
            return ((b[0] & 0xff) << 8) | (b[1] & 0xff);
        } else if (b.length == 3) {
            return ((b[0] & 0xff) << 16) | ((b[1] & 0xff) << 8) | (b[2] & 0xff);
        } else if (b.length >= 4) {
            ByteBuffer converter = ByteBuffer.wrap(b);
            converter.order(ByteOrder.nativeOrder());
            return converter.getInt();
        } else {
            throw new RuntimeException("byte length > 4 or < 1");
        }
    }

    public static byte[] convertStringIpToBytes(String ipAdress) {
        String[] ips = ipAdress.split("\\.");
        byte[] bytes = new byte[4];
        for (int i = 0; i < ips.length; i++) {
            bytes[i] = (byte) (Integer.parseInt(ips[i]));
        }
        return bytes;
    }
}
